package com.wangsd.web.coupon.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.enums.ResultCode;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.web.MyController;
import com.wangsd.web.coupon.entity.*;
import com.wangsd.web.coupon.service.*;
import com.wangsd.web.coupon.vo.WxPay;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.wangsd.common.enums.ResultCode.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-09-10
 */
@Api(value = "wxProduct", tags = "微信商品信息")
@RestController
@RequestMapping("/coupon/wxProduct")
@Slf4j
public class WxProductController extends MyController {

    @Autowired
    CompanyService companyService;

    @Autowired
    ProductService productService;

    @Autowired
    CouponService couponService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    StoreService storeService;

    @Autowired
    MemberService memberService;

    @Autowired
    MemberCouponService memberProductService;

    @Autowired
    MemberCouponService memberCouponService;

    @Autowired
    WxMiniPayService wxMiniPayService;

    @Autowired
    TOrderService tOrderService;

    @Autowired
    ServiceBusinessService serviceBusinessService;

    @Autowired
    ActivityProductService activityProductService;

    @Autowired
    NewGiftService newGiftService;

    @Autowired
    BusinessCouponService businessCouponService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Value("${notify_url}")
    private String notify_url;

    @ApiOperation(value = "查询商品列表", notes = "查询商品列表", httpMethod = "POST")
    @PostMapping("/getProductList/{pageNum}/{pageSize}")
    public Result getProductList(@PathVariable Integer pageNum,
                                 @PathVariable Integer pageSize,
                                 @RequestBody Product params) {
        Company company = companyService.selectByMiniAppid(getMiniAppid());
        params.setCompanyId(company.getId());
        /*查询已上架商品*/
        params.setState(1);
        IPage<Product> productIPage = productService.selectPage(null, pageNum, pageSize, params);
        List<Product> records = productIPage.getRecords();
        if (records != null && records.size() > 0) {
            Long time = System.currentTimeMillis();
            for (Product product : records) {
                product.setIsExpired(DateUtils.paseDatetime(product.getEndTime()).getTime() <= time ? 1 : 0);
            }
        }
        return Result.success(productIPage);
    }

    @ApiOperation(value = "查询商家券列表", notes = "查询商家券列表", httpMethod = "POST")
    @PostMapping("/getBusinessCouponList/{pageNum}/{pageSize}")
    public Result getBusinessCouponList(@PathVariable Integer pageNum,
                                 @PathVariable Integer pageSize,
                                 @RequestBody BusinessCoupon params) {
        Company company = companyService.selectByMiniAppid(getMiniAppid());
        params.setCompanyId(company.getId());
        params.setState(1);
        /*查询已上架商品*/
        IPage<BusinessCoupon> productIPage = businessCouponService.selectPage(null, pageNum, pageSize, params);
        return Result.success(productIPage);
    }

    @ApiOperation(value = "查询商家券爆款列表", notes = "查询商家券爆款列表", httpMethod = "POST")
    @PostMapping("/getHTypeBusinessCouponList")
    public Result getHTypeBusinessCouponList(@RequestBody BusinessCoupon params) {
        /*查询已精品团购券*/
        params.setHType(1);
        List<BusinessCoupon> businessCoupons = businessCouponService.selectAll(params);
        return Result.success(businessCoupons);
    }

    @ApiOperation(value = "查询商家券详情", notes = "查询商家券详情", httpMethod = "GET")
    @GetMapping("/getBusinessCouponDetail/{id}")
    public Result getBusinessCouponDetail(@PathVariable String id) {
        BusinessCoupon businessCoupon = businessCouponService.getById(id);
        return Result.success(businessCoupon);
    }

    @ApiOperation(value = "查询商品详情", notes = "查询商品详情", httpMethod = "GET")
    @GetMapping("/getProductDetail/{id}")
    public Result getProductDetail(@PathVariable String id) {
        Product product = productService.getById(id);
        if(product==null){
            return Result.fail("该商品不存在");
        }
        Store store = storeService.getById(product.getStoreId());
        product.setStore(store);
        return Result.success(product);
    }

    @ApiOperation(value = "查询优惠券列表", notes = "查询优惠券列表", httpMethod = "POST")
    @PostMapping("/getCouponList/{pageNum}/{pageSize}")
    public Result getCouponList(@PathVariable Integer pageNum,
                                @PathVariable Integer pageSize,
                                @RequestBody Coupon params) {
        Company company = companyService.selectByMiniAppid(getMiniAppid());
        params.setCompanyId(company.getId());
        /*查询已上架优惠券*/
        params.setState(1);
        IPage<Coupon> productIPage = couponService.selectPage(null, pageNum, pageSize, params);
        List<Coupon> records = productIPage.getRecords();
        if (records != null && records.size() > 0) {
            Long time = System.currentTimeMillis();
            for (Coupon coupon : records) {
                coupon.setIsExpired(DateUtils.paseDatetime(coupon.getEndTime()).getTime() <= time ? 1 : 0);
            }
        }
        return Result.success(productIPage);
    }

    @ApiOperation(value = "查询优惠券详情", notes = "查询优惠券详情", httpMethod = "GET")
    @GetMapping("/getCouponDetail/{id}")
    public Result getCouponDetail(@PathVariable String id) {
        Coupon coupon = couponService.getById(id);
        List<Store> stores = storeService.selectByCouponId(id);
        coupon.setStores(stores);
        return Result.success(coupon);
    }

    @ApiOperation(value = "查询优惠券可使用门店", notes = "查询优惠券可使用门店", httpMethod = "GET")
    @GetMapping("/getUseStore")
    public Result getUseStore(String productId) {
        List<Store> list = storeService.selectByCouponId(productId);
        return Result.success(list);
    }

    @ApiOperation(value = "查询当前用户领取的优惠券", notes = "查询当前用户领取的优惠券", httpMethod = "POST")
    @PostMapping("/getHaveProduct/{pageNum}/{pageSize}")
    public Result getHaveProduct(@PathVariable Integer pageNum,
                                 @PathVariable Integer pageSize,
                                 Integer state) {
        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }
        String openid = miniUserInfo.getMiniOpenid();

        if (state == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "优惠卷状态" + PRARM_NOT_NULL.getMessage());
        }
        IPage<Coupon> haveCoupon = couponService.getHaveCoupon(pageNum, pageSize, openid, state);
        return Result.success(haveCoupon);
    }

    @ApiOperation(value = "领取优惠券", notes = "领取优惠券", httpMethod = "GET")
    @GetMapping("/receiveCoupon")
    public Result receiveCoupon(String productId, Integer type) {
        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }

        Coupon coupon = couponService.getById(productId);
        if (coupon == null) {
            return Result.fail("优惠券不存在");
        }
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        if (nowTime.compareTo(coupon.getEndTime()) > 0) {
            return Result.fail("该商品活动时间超过使用时间！");
        }

        /*验证每个用户能领取的数量*/
        Integer count = memberCouponService.selectByProductIdAndOpenid(productId, miniUserInfo.getMiniOpenid());
        if (coupon.getMaxQuota() != 0) {
            if (coupon.getMaxQuota() <= count) {
                return Result.fail("每个人最多能领取" + coupon.getMaxQuota() + "张优惠券");
            }
        }

        if (type != null) {
            if (1 == type) {//限时抢购
                Result result = validateOutTime(productId, 0);
                if (result != null) {
                    return result;
                }
            } else if (2 == type) {//新人礼
                Result result = validateNewGift(productId, coupon.getCompanyId(), miniUserInfo.getMiniOpenid(), 0);
                if (result != null) {
                    return result;
                }
            } else if (3 == type) {//大转盘
                // TODO: 2019/10/23
            }
        }

        /*发放优惠卷*/
        Company company = companyService.getById(coupon.getCompanyId());
        ServiceBusiness serviceBusiness = serviceBusinessService.getById(company.getBusinessServiceId());
        Member member = memberService.getOne(new QueryWrapper<Member>().eq("mini_openid", miniUserInfo.getMiniOpenid()));
        try {
            int i = couponService.quickReceiveCoupon(serviceBusiness, coupon, member, company);
            if (-1 == i) {
                return Result.fail("优惠卷发放失败");
            }
        } catch (BusinessException e) {
            if (e.getCode() == 9001) {
                Map<String, String> map = new HashMap<>();
                map.put("serviceAppId", company.getMiniAppid());
                map.put("from", notify_url + "/notify/memberAuthCallBack");
                return new Result(7006, "请先进行授权", map);
            } else {
                log.error("businessException", e);
                return Result.fail(e.getMessage());
            }
        } catch (Exception e) {
            log.error("Exception", e);
            return Result.fail("优惠卷发放失败");
        }
        return Result.success();
    }


    @ApiOperation(value = "一键领取优惠券", notes = "一键领取优惠券", httpMethod = "GET")
    @GetMapping("/quickReceiveCoupon")
    public Result quickReceiveCoupon() {

        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }
        String openid = miniUserInfo.getMiniOpenid();


        if (StringUtils.isBlank(openid)) {
            return Result.fail(PRARM_NOT_NULL.getCode(), "openid不能为空");
        }
        Member member = memberService.selectByOpenid(openid);

        /*通过小程序appid获取到服务商信息*/
        Company company = companyService.selectByMiniAppid(getMiniAppid());
        ServiceBusiness serviceBusiness = serviceBusinessService.getById(company.getBusinessServiceId());
        if (serviceBusiness == null) {
            return Result.fail(PRARM_NOT_NULL.getCode(), "服务商未配置");
        }

        /*查询当前可以领取的优惠券*/
        Coupon couponQuery = new Coupon();
        couponQuery.setCompanyId(company.getId());
        List<Coupon> coupons = couponService.selectCouponListByCompanyId(couponQuery);
        if (coupons == null || coupons.size() <= 0) {
            return new Result(9001, "失败！", "没有可以领取的优惠卷");
        }

        /*循环处理领取优惠券*/
        StringBuffer stringBuffer = new StringBuffer();
        int successCount = 0;
        for (Coupon coupon : coupons) {
            for (int i = 0; i < coupon.getMaxQuota(); i++) {
                int result = -1;
                try {
                    result = couponService.quickReceiveCoupon(serviceBusiness, coupon, member, company);
                } catch (BusinessException e) {
                    if (9001 == e.getCode()) {
                        return new Result(9001, "失败！", e.getMessage());
                    } else if (9002 == e.getCode()) {
                        return new Result(9002, "失败！", e.getMessage());
                    }
                } catch (Exception e) {
                    log.error("quickReceiveCoupon:", e);
                }
                if (result != -1) {
                    successCount++;
                }
            }

        }
        stringBuffer.append("成功领取优惠卷 ").append(successCount).append(" 张");
        return Result.success(stringBuffer);
    }


    @ApiOperation(value = "微信支付调用", notes = "微信支付调用", httpMethod = "POST")
    @PostMapping("/wxPay")
    public Result wxPay(@RequestBody WxPay wxPay, HttpServletRequest request) {
        String productId = wxPay.getProductId();
        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }
        String openid = miniUserInfo.getMiniOpenid();

        if (productId == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "商品id" + PRARM_NOT_NULL.getMessage());
        }

        Member member = memberService.selectByOpenid(openid);
        if (member == null) {
            return Result.fail("请先进行会员登录！！");
        }
        /*if (member.getPayOpenid() == null) {
            return Result.message(MINI_APP_USER_NO_AUTH);
        }*/

        Product product = productService.getById(productId);
        if (product == null) {
            return Result.fail("商品不存在！！");
        }

        if (product.getType() == 2) {
            String payOpenid = stringRedisTemplate.opsForValue().get(openid);
            if (StringUtils.isBlank(payOpenid)) {
                Long companyId = product.getCompanyId();
                Company byId = companyService.getById(companyId);
                ServiceBusiness serviceBusiness = serviceBusinessService.getById(byId.getBusinessServiceId());
                Map<String, String> map = new HashMap<>();
                map.put("serviceAppId", serviceBusiness.getAppId());
                map.put("from", notify_url + "/notify/memberAuthCallBack");
                return new Result(7006, "请先进行授权", map);
            }
        }

        if (product.getUsableProductCount() <= 0) {
            return Result.fail("商品数量不足！");
        }

        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (nowTime.compareTo(product.getEndTime()) > 0) {
            return Result.fail("不在活动时间！");
        }

        Integer type = wxPay.getType();
        if (type != null && 1 == type) {//限时抢购
            Result result = validateOutTime(productId, 1);
            if (result != null) {
                return result;
            }
        } else if (type != null && 2 == type) {//新人礼
            Result result = validateNewGift(productId, product.getCompanyId(), miniUserInfo.getMiniOpenid(), 1);
            if (result != null) {
                return result;
            }
        } else if (type != null && 3 == type) {//大转盘
            // TODO: 2019/10/23
        }


        try {
            final Store store = storeService.getById(product.getStoreId());
            if (store == null) {
                return Result.fail("商品未关联门店");
            }
            Merchant merchant = merchantService.getById(store.getMerchantId());
            product.setSubMchId(merchant.getSubMchId());

            Object object = wxMiniPayService.wxPay(wxPay.getAddress(), product, getMiniAppid(), member, request);
            if (object == null) {
                return Result.message(MINI_APP_PAY_SIGN_PRARM);
            }
            return Result.success(object);
        } catch (Exception e) {
            log.error("wxPay", e);
        }

        return Result.message(MINI_APP_PAY_SIGN_PRARM);
    }

    @ApiOperation(value = "微信支付购买商家券调用", notes = "微信支付购买商家券调用", httpMethod = "POST")
    @PostMapping("/wxBusinessCouponPay")
    public Result wxBusinessCouponPay(@RequestBody WxPay wxPay, HttpServletRequest request) {
        String productId = wxPay.getProductId();
        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }
        String openid = miniUserInfo.getMiniOpenid();

        if (productId == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "商品id" + PRARM_NOT_NULL.getMessage());
        }

        Member member = memberService.selectByOpenid(openid);
        if (member == null) {
            return Result.fail("请先进行会员登录！！");
        }
        /*if (member.getPayOpenid() == null) {
            return Result.message(MINI_APP_USER_NO_AUTH);
        }*/

        BusinessCoupon businessCoupon = businessCouponService.getById(productId);
        if (businessCoupon == null) {
            return Result.fail("商家券不存在！！");
        }

        /*String payOpenid = stringRedisTemplate.opsForValue().get(openid);
        if (StringUtils.isBlank(payOpenid)) {
            Long companyId = businessCoupon.getCompanyId();
            Company byId = companyService.getById(companyId);
            ServiceBusiness serviceBusiness = serviceBusinessService.getById(byId.getBusinessServiceId());
            Map<String, String> map = new HashMap<>();
            map.put("serviceAppId", serviceBusiness.getAppId());
            map.put("from", notify_url + "/notify/memberAuthCallBack");
            return new Result(7006, "请先进行授权", map);
        }*/

        if (businessCoupon.getUsableBusinessCouponCount() <= 0) {
            return Result.fail("商家券数量不足！");
        }

        /*String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (nowTime.compareTo(product.getEndTime()) > 0) {
            return Result.fail("不在活动时间！");
        }*/

        /*Integer type = wxPay.getType();
        if (type != null && 1 == type) {//限时抢购
            Result result = validateOutTime(productId, 1);
            if (result != null) {
                return result;
            }
        } else if (type != null && 2 == type) {//新人礼
            Result result = validateNewGift(productId, product.getCompanyId(), miniUserInfo.getMiniOpenid(), 1);
            if (result != null) {
                return result;
            }
        } else if (type != null && 3 == type) {//大转盘
            // TODO: 2019/10/23
        }*/


        try {

            Object object = wxMiniPayService.wxBusinessCouponPay(wxPay.getAddress(), businessCoupon, getMiniAppid(), member, request);
            if (object == null) {
                return Result.message(MINI_APP_PAY_SIGN_PRARM);
            }
            return Result.success(object);
        } catch (Exception e) {
            log.error("wxPay", e);
        }

        return Result.message(MINI_APP_PAY_SIGN_PRARM);
    }

    @ApiOperation(value = "微信小程序积分兑换", notes = "微信小程序积分兑换", httpMethod = "GET")
    @GetMapping("/exchangePoints")
    @ResponseBody
    public Result exchangePoints(String productId) {
        if (productId == null) {
            return Result.fail("商品id参数错误！");
        }

        Product product = productService.getById(productId);
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (!((nowTime.compareTo(product.getBeginTime()) > 0) && (nowTime.compareTo(product.getEndTime()) < 0))) {
            return Result.fail("商品已过期");
        }

        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }

        String openid = miniUserInfo.getMiniOpenid();
        Member member = memberService.selectByOpenid(openid);
        if (product.getValue() > member.getIntegral()) {
            return Result.fail("积分余额不足!");
        }
        Integer object = null;

        try {
            object = wxMiniPayService.exchangePoints(product, getMiniAppid(), member);
        } catch (WxPayException e) {
            return Result.fail(e.getCustomErrorMsg());
        } catch (Exception e) {
            return Result.fail("优惠卷兑换失败");
        }
        return Result.success(object);
    }

    @ApiOperation(value = "微信小程序支付回调通知支付", notes = "微信小程序支付回调通知支付", httpMethod = "GET")
    @RequestMapping(value = "/wxNotify")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("微信支付回调通知开始");
        try {
            wxMiniPayService.wxNotify(request, response);
        } catch (Exception e) {
            log.error("wxNotify", e);
        }
        log.info("微信支付回调通知结束");
    }

    @ApiOperation(value = "微信小程序购买商家券支付回调通知支付", notes = "微信小程序购买商家券支付回调通知支付", httpMethod = "GET")
    @RequestMapping(value = "/wxBusinessCouponNotify")
    public void wxBusinessCouponNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("微信小程序购买商家券支付回调通知支付");
        try {
            wxMiniPayService.wxBusinessCouponNotify(request, response);
        } catch (Exception e) {
            log.error("wxBusinessCouponNotify", e);
        }
        log.info("微信小程序购买商家券支付回调通知支付");
    }


    @ApiOperation(value = "商家券领券事件回调通知", notes = "商家券领券事件回调通知", httpMethod = "GET")
    @RequestMapping(value = "/getBusinessCouponNotify")
    public void getBusinessCouponNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("商家券领券事件回调通知");
        try {
            wxMiniPayService.getBusinessCouponNotify(request, response);
        } catch (Exception e) {
            log.error("getBusinessCouponNotify", e);
        }
        log.info("商家券领券事件回调通知");
    }

    @ApiOperation(value = "微信小程序购买订单列表查询", notes = "微信小程序购买订单列表查询", httpMethod = "POST")
    @PostMapping("/selectWxOrder/{pageNum}/{pageSize}")
    @ResponseBody
    public Result selectWxOrder(@PathVariable Integer pageNum,
                                @PathVariable Integer pageSize,
                                @RequestBody TOrder tOrder) {
        Member miniUserInfo = getMiniUserInfo();
        if (miniUserInfo == null) {
            return new Result(NO_LOGIN);
        }
        tOrder.setOpenid(miniUserInfo.getMiniOpenid());
        tOrder.setCompanyId(miniUserInfo.getCompanyId());
        try {
            IPage<TOrder> tOrderIPage = tOrderService.selectWxOrder(pageNum, pageSize, tOrder);
            return Result.success(tOrderIPage);
        } catch (Exception e) {
            log.error("selectWxOrder", e);
        }
        return Result.fail("微信小程序购买订单列表查询！！");
    }

    /**
     * 微信退款调用
     *
     * @return
     */
    @ApiOperation(value = "微信退款调用", notes = "微信退款调用", httpMethod = "POST")
    @PostMapping("/refund")
    public Object refund(String orderId, HttpServletRequest request) {

        if (orderId == null) {
            return new Result(9000, "缺少参数", "");
        }
        TOrder tOrder = tOrderService.getOne(new QueryWrapper<TOrder>().eq("transaction_id", orderId));
        if (tOrder == null) {
            return Result.message(MINI_APP_ORDER_NOT_EXIST);
        }

        String object = null;
        try {
            object = wxMiniPayService.refund(tOrder, getMiniAppid(), orderId, request);
        } catch (WxPayException e) {
            log.error("refund", e);
            return Result.fail(e.getCustomErrorMsg());
        } catch (Exception e) {
            log.error("refund", e);
            return Result.fail(e.getMessage());
        }

        if ("noAuth".equals(object)) {
            return Result.fail("无法发起退款！");
        } else if (object.contains("ERROR") || object.contains("error")) {
            return Result.fail(object);
        }

        return Result.success("退款成功！！");
    }

    @ApiOperation(value = "微信查询优惠券或商品详情", notes = "微信查询优惠券或商品详情", httpMethod = "POST")
    @PostMapping("/getObjectDetail")
    public Result getObjectDetail(@RequestBody Product params) {
        Integer type = params.getType();
        if (type == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "类型不能为空");
        }
        String productId = params.getId();
        if (StringUtils.isBlank(productId)) {
            return new Result(PRARM_NOT_NULL.getCode(), "商品或者优惠券id不能为空");
        }
        if (0 == type) {//优惠券
            Coupon coupon = couponService.getById(productId);
            List<Store> stores = storeService.selectByCouponId(coupon.getId());
            coupon.setStores(stores);
            return Result.success(coupon);
        } else {//商品
            Product product = productService.getById(productId);
            Store store = storeService.getById(product.getStoreId());
            product.setStore(store);
            return Result.success(product);
        }
    }

    /**
     * 验证限时 优惠券领取
     */
    private Result validateOutTime(String productId, Integer type) {
        /*验证限时秒杀*/
        Date now = new Date();
        ActivityProduct activityProduct = activityProductService.selectActivityProductByProductId(productId, type);
        if (activityProduct != null) {
            if ((-1 == now.compareTo(activityProduct.getBeginTime())) || (-1 != now.compareTo(activityProduct.getEndTime()))) {
                return Result.fail("不在限时秒杀活动期间！");
            }
        }
        return null;
    }

    /**
     * 验证新人礼 优惠券领取
     */
    private Result validateNewGift(String productId, Long companyId, String openid, Integer type) {
        /*验证新人礼*/
        Date now = new Date();
        NewGift newGift = newGiftService.selectNewGiftByProductId(productId, type);
        if (newGift != null) {
            if ((-1 == now.compareTo(newGift.getBeginTime())) || (-1 != now.compareTo(newGift.getEndTime()))) {
                return Result.fail("不在限时秒杀活动期间！");
            }
            /*优惠券需要验证*/
            if (type == 0) {
                List<String> list = newGiftService.selectNewGiftProductByCompanyId(companyId, newGift.getActivityType());
                if (list != null) {
                    Long aLong = memberProductService.selectNewGiftByProductIdAndOpenid(list, openid);
                    if (aLong > 0) {
                        return Result.fail("一个用户活动期间只能领取一张优惠卷！");
                    }
                }
            }
        }
        return null;
    }
}